// pages/myInformation/myInformation.js
const util = require('../../utils/util');
const API = require('../../common/constant');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    info: {},
    food: [],
    music: [],
    movies: [],
    book: [],
    place: [],
    sports: [],
    threeImages: [],
    shownameAuthStatus: true,
    marks: ['swas', 'swasw', 'sawdawf', 'ea', 'feafwfw', 'swad'],
    comments: [
      {
        avatar: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1530382786514&di=81c8ae52045473061eddeb1fd300ca07&imgtype=0&src=http%3A%2F%2Fupload.chinaz.com%2F2017%2F0215%2F6362277039299430564928734.jpeg',
        name: '无知少女',
        sign: '别担心交给我吧',
        time: '24小时前',
        music: ['夏家三千菜', 'legends never die', '好饿啊']
      }, {
        avatar: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1530382786514&di=81c8ae52045473061eddeb1fd300ca07&imgtype=0&src=http%3A%2F%2Fupload.chinaz.com%2F2017%2F0215%2F6362277039299430564928734.jpeg',
        name: '无知少女',
        sign: '别担心交给我吧',
        time: '24小时前',
        music: ['夏家三千菜', 'legends never die', '好饿啊']
      }
    ]
  },
  toMoreEva: function () {
    wx.navigateTo({
      url: '../evaluate/index?id='+ this.data.info.id,
    })
  },
  /**
   * 跳转到实名认证页面
   */
  toNameAuth: function (e) {
    wx.navigateTo({
      url: '../nameAuthentication/nameAuthentication'
    })
  },
  /**
   * 隐藏身份认证
   */
  hidenameAuth: function (e) {
    this.setData({
      shownameAuthStatus: false
    })
  },
  /**
   * 获取用户基本信息
   */
  getUserInfo() {
    var that = this;
    util.http({
      url: API.URL.USER.FIND_USERINFO,
      success: res => {
        console.log(res.data);
        let marks = []
        let array = res.data.bussData.pageData.bussData
        let comments = []
        array.forEach((item, index) => {
          comments.push({
            avatar: array[index].attachmentUrl,
            name: array[index].nickname,
            sign: array[index].content,
            time: array[index].gmtCreated
          })
          marks.push(array[index].sign)
        })
        let newData = this.ChangeInfoLabel(res.data.bussData);
        this.changeHobby(newData.hobby);
        newData = this.changeActivityType(res.data.bussData);
        if (newData.isRealname === 'y'){
          that.setData({
            shownameAuthStatus: false
          })
        }
        that.setData({
          info: newData,
          comments: comments,
          marks: marks
        });
        that.getThreeImages();
      },
      fail: rej => {
        console.log(rej);
      }
    })
  },
  /**
   * 修改hobby
   */
  changeHobby: function (data) {
    if (typeof (data) == 'undefined') {
      return;
    }
    let currentHobbies = data.split('[')[1].split(']')[0].split(',')[0].split('{');
    let temp, t; // 临时变量
    let food = [], music = [], movies = [], book = [], place = [], sports = [];
    for (let i = 1; i < currentHobbies.length; i++) {
      temp = currentHobbies[i].split(':');
      t = temp[1].split('"')[1].split('，');
      switch (temp[0]) {
        case '"饮食"': food = t; break;
        case '"音乐"': music = t; break;
        case '"电影"': movies = t; break;
        case '"书"': book = t; break;
        case '"地方"': place = t; break;
        case '"运动"': sports = t; break;
      }
      t = [];
    }
    this.setData({
      food: food,
      music: music,
      movies: movies,
      book: book,
      place: place,
      sports: sports
    });
  },
  /**
   * 修改用户标签
   */
  ChangeInfoLabel: function (data) {
    let newdata = data;
    newdata.labels = [];
    if (typeof (data.label) == 'undefined') {
      return newdata;
    } else if (data.label.length == 0) {
      return newdata;
    } else {
      let labels = data.label.split(';');
      for (let i = 0; i < labels.length; i++) {
        newdata.labels.push(
          {
            'text': labels[i]
          });
      }
      return newdata;
    }
  },
  /**
   * 修改活动类型
   */
  changeActivityType: function (data) {
    if (data.eventType == "chat") {
      data.activityType = "#解闷聊天#";
      data.activityColor = '#F4BC11';
    } else if (data.eventType == "partner") {
      data.activityType = "#美食搭伙#";
      data.activityColor = '#FF8023';
    } else if (data.eventType == 'find') {
      data.activityType = "#求邂逅#";
      data.activityColor = '#FE3232';
    }
    return data;
  },
  /**
   * 跳转到 他的相册
   */
  toAlbum: function (e) {
    wx.navigateTo({
      url: '../myPhotos/myPhotos'
    });
  },
  /**
   * 修改个人背景
   */
  changeBack: function (e) {
    let that = this;
    wx.chooseImage({
      count: 1, // 默认9
      header: { "Content-Type": "multipart/form-data" },
      success: function (res) {
        console.log('chooseImage Api成功', res)
        var tempFilePaths = res.tempFilePaths[0];
        wx.showLoading({
          title: '正在上传',
        })
        wx.uploadFile({
          url: API.URL.SYS.UPLOAD_FILE,
          filePath: tempFilePaths,
          name: 'file',
          formData: {
            sessionId: wx.getStorageSync('sessionId')
          },
          success: res => {
            console.log(JSON.parse(res.data));
            let file = JSON.parse(res.data).data.bussData;
            wx.hideLoading();
            console.log('uploadFile Api成功', file);
            util.http({
              url: API.URL.USER.EDIT_MINIUSERINFO,
              data: {
                'fileInfo.fileKey': file.fileKey
              },
              success: res => {
                wx.hideLoading();
                console.log('接口调用成功', res);
                that.setData({
                  ['info.fileUrl']: file.fileUrl
                })
              },
              fail: err => {
                wx.hideLoading();
                console.log('接口调用失败', err);                
              }
            })
          },
          fail: err => {
            console.log('22222222222222');            
            wx.hideLoading();
            console.log('uploadFile Api失败', err);
          }
        });
        console.log('bugbugbugbug');
      },
      fail: err =>{
        console.log('chooseImage Api失败', err)
      }
    })
  },
  /**
   * 获取三张图片
   */
  getThreeImages: function () {
    // console.log(this.data.info);
    let allImages = this.data.info.imageDTOList;
    // console.log(allImages);
    let count = 0;
    let threeImages = [];
    for (let i = 0; i < allImages.length; i++) {
      if (count >= 3) break;
      threeImages.push(allImages[i].fileUrl);
      count++;
    }
    console.log(threeImages);
    this.setData({
      threeImages: threeImages
    })
  },
  /**
   * 跳转到标签页面
   */
  toEditTags: function () {
    wx.navigateTo({
      url: '../userTags/userTags?tags=' + this.data.info.label
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.globalData.isNewMyInfo = false;
    this.getUserInfo();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.isNewMyInfo){
      this.getUserInfo();
      app.globalData.isNewMyInfo = false;
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // wx.switchTab({
    //   url: '../my/my'
    // });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})